package com.projectsquirrel;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.ToggleButton;

public class settingsMenu extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.settingsscreen);
	    final SharedPreferences pref = getSharedPreferences("AppSettings",MODE_PRIVATE);
  
	    String userEmail = pref.getString("userEmail", null);
	    
	    final EditText emailTextField = (EditText) findViewById(R.id.emailText);
	    final ToggleButton toggleDateTimeLoc = (ToggleButton) findViewById(R.id.DateAndTimeToggle);
	    emailTextField.setHint(userEmail);
	    
	    ImageButton infoIconButton = (ImageButton) findViewById(R.id.infoScreenIcon);
	    Button saveButton = (Button) findViewById(R.id.saveButton);
	    
	    
	    boolean isOverwrite = pref.getBoolean("OverwriteDateTimeLoc", false);
	    if(isOverwrite){
	    	toggleDateTimeLoc.setChecked(true);
	    }
	    infoIconButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(settingsMenu.this, infoMenu.class);
		        startActivity(i);
			}	    	
	    });	    
	    saveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences.Editor editor = pref.edit();  
				editor.putBoolean("OverwriteDateTimeLoc", toggleDateTimeLoc.isChecked());
				editor.commit();
				String emailText = emailTextField.getText().toString();
				String regTest="([\\w-+]+(?:\\.[\\w-+]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7})";
				Pattern p = Pattern.compile(regTest,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
			    Matcher m = p.matcher(emailText);
			    if(emailText.equalsIgnoreCase("")){	
			    	finish();
			    }
			    else if (!m.find()){
			    	Toast.makeText(getApplicationContext(),"Please Enter a valid email address",Toast.LENGTH_LONG).show();
			    } 
			    else{
			    	editor = pref.edit();  
					editor.putString("userEmail", emailText);
					editor.commit();
					finish();
			    }
			}		
	    });
	    

	}
}